﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dln.Business;
using Dln.Common;
using Dln.Common.Helper;
using Dln.Handler;
using Dln.Model;

public partial class _test : System.Web.UI.Page
{

    public string appid = string.Empty, time = string.Empty, noncestr = string.Empty, resp = string.Empty;
    public string backUrl = string.Empty;

    public object ticket = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        //var uptModel = SqlHelper.Context.From<WeChatUsers>().Where(d => d.ISSendWeChat1 == 1).ToList();
        //if (uptModel != null && uptModel.Count > 0)
        //{
        //    foreach (var item in uptModel)
        //    {
        //        MessageHelper.OrderPayNotice(item.Openid,
        //                        "患者统计",
        //                       DateTime.Now.ToString("yyyy - MM - dd HH: mm:ss"),
        //                       "1",
        //                       "点击通知查看详细，如有任何疑问直接回复公众号。",
        //                        "http://www.healthyperson.cn/Page/AutoUpdate/WeChatStatics.aspx?NowDateTime=" + DateTime.Now.Date
        //                    );
        //    }
        //}

        //var weChatUsersList = SqlHelper.Context.FromSql(string.Format("select * from WeChatUsers where charindex(',{0},',',' + Category + ',')>0 ", 18)).ToList<WeChatUsers>();
        //backUrl = "http://" + Request.Url.Host + Request.RawUrl;
        //Hashtable ht = GetShare(backUrl);
        //if (ht != null)
        //{
        //    appid = ht["appid"] == null ? "" : ht["appid"].ToString();
        //    time = ht["time"] == null ? "" : ht["time"].ToString();
        //    noncestr = ht["noncestr"] == null ? "" : ht["noncestr"].ToString();
        //    resp = ht["resp"] == null ? "" : ht["resp"].ToString();
        //}



    }

    public class GetTicket
    {
        public string errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public string expires_in { get; set; }
    }

    public static Hashtable GetShare(string url)
    {
        try
        {
            string AppID = CommonHelper.GetAppSettings("AppID");
            string AppSecret = CommonHelper.GetAppSettings("AppSecret");
            string strMainUrl = CommonHelper.GetAppSettings("mainurl");
            string appid = AppID;
            string appsecret = AppSecret;
            string noncestr = RandString();
            string time = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
            var cookies = HttpContext.Current.Request.Cookies["ticket"];
            string ticket = string.Empty;
            if (cookies != null && !string.IsNullOrEmpty(cookies.Value))
            {
                ticket = cookies.Value;
            }
            else
            {
                string newjson =
                        RequestHelper.SendGet(
                            String.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi",
                                TokenBussiness.GetTokenKey()));
                
                GetTicket getticket = null;
                if (!String.IsNullOrEmpty(newjson))
                {
                    try
                    {
                        getticket = JSONHelper.FromJson<GetTicket>(newjson);
                        ticket = getticket.ticket;

                        HttpCookie cookie = new HttpCookie("ticket");
                        cookie.Value = ticket;
                        cookie.Expires = DateTime.Now.AddMinutes(110);
                        HttpContext.Current.Response.Cookies.Add(cookie);
                    }
                    catch (Exception ex)
                    {

                    }
                }
                
            }
            string string1 = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", ticket, noncestr, time, url);
            string resp = SHA1(string1);
            Hashtable ht = new Hashtable();
            ht["appid"] = appid;
            ht["time"] = time;
            ht["noncestr"] = noncestr;
            ht["resp"] = resp;
            return ht;
        }
        catch (Exception ex)
        {
            Hashtable ht = new Hashtable();
            ht["appid"] = "";
            ht["time"] = "";
            ht["noncestr"] = "";
            ht["resp"] = "";
            return ht;
        }
    }

    protected static string RandString()
    {
        string str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+";//75个字符
        Random r = new Random();
        string result = string.Empty;

        //生成一个8位长的随机字符，具体长度可以自己更改
        for (int i = 0; i < 16; i++)
        {
            int m = r.Next(0, 75);//这里下界是0，随机数可以取到，上界应该是75，因为随机数取不到上界，也就是最大74，符合我们的题意
            string s = str.Substring(m, 1);
            result += s;
        }

        return result;
    }
    private static string SHA1(string text)
    {
        byte[] cleanBytes = Encoding.Default.GetBytes(text);
        byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);
        return BitConverter.ToString(hashedBytes).Replace("-", "");
    }
}